package com.qqt.csr.common.utils;

import com.qqt.csr.common.acl.auth.resp.AuthInfoDTO;
import com.qqt.csr.common.vo.req.RequestHeader;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author:
 * @date: 2024-07-04 11:25
 */
public class HttpRequestHeaderUtil {

    public static RequestHeader buildRequestHeader(AuthInfoDTO authInfoDto) {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if (httpServletRequest == null) {
            return null;
        }

        RequestHeader requestHeader = new RequestHeader()
                .setSysCode(httpServletRequest.getHeader(RequestHeader.SYS_CODE))
                .setLang(httpServletRequest.getHeader(RequestHeader.LANG))
                .setDeviceFlag(httpServletRequest.getHeader(RequestHeader.DEVICE_FLAG))
                .setToken(httpServletRequest.getHeader(RequestHeader.TOKEN))
                .setAccessToken(httpServletRequest.getHeader(RequestHeader.ACCESS_TOKEN))
                .setDeviceType(httpServletRequest.getIntHeader(RequestHeader.DEVICE_TYPE))
                .setOs(httpServletRequest.getHeader(RequestHeader.OS))
                .setFrom(httpServletRequest.getHeader(RequestHeader.FROM))
                .setVersion(httpServletRequest.getHeader(RequestHeader.VERSION))
                .setLongitude(httpServletRequest.getHeader(RequestHeader.LONGITUDE))
                .setLatitude(httpServletRequest.getHeader(RequestHeader.LATITUDE))
                .setTenantId(httpServletRequest.getHeader(RequestHeader.TENANT_ID))
                ;
        if(authInfoDto!=null){
            requestHeader.setUserId(authInfoDto.getUserId())
                    .setUserName(authInfoDto.getAccount())
                    .setNickName(authInfoDto.getNickName())
                    .setHeadImgUrl(authInfoDto.getHeadImg())
                    .setAuthInfoDTO(authInfoDto);
        }else{
            requestHeader.setUserId(0L)
                    .setUserName("system")
                    .setNickName("system")
                    .setHeadImgUrl(StringUtils.EMPTY);
        }
        return requestHeader;
    }

    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }
}
